package com.gator.rabbitmq.pablo_rabbitmq.boot.rabbitmq.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author PABLO
 * @Date 2022/6/6 18:23
 * @Desc 基于交换机失效的发布确认机制
 */
@Configuration
public class PublishConfirmConfig {

    public static final String CONFIRM_EXCHANGE_NAME = "confirm_exchange";

    public static final String CONFIRM_QUEUE_NAME = "confirm_queue";

    public static final String CONFIRM_ROUTING_KEY = "confirm_key";

    /**
     * @Description: 确认交换机将无效key转发到备份交换机上
     * @Author: PABLO
     * @Date: 2022/6/6 20:58
     * @Params: []
     * @Return: org.springframework.amqp.core.DirectExchange
     **/
    @Bean
    public DirectExchange confirmDirectExchange() {
        Map<String, Object> arguments = new HashMap<>();
        //指向备份交换机
        arguments.put("alternate-exchange", BACKUP_EXCHANGE_NAME);
        return ExchangeBuilder.directExchange(CONFIRM_EXCHANGE_NAME).withArguments(arguments).build();
    }

    @Bean
    public Queue confirmQueue() {
        return QueueBuilder.durable(CONFIRM_QUEUE_NAME).build();
    }

    //绑定交换机和队列指定路由key
    @Bean
    public Binding queueBindingExchange(@Qualifier("confirmDirectExchange") DirectExchange confirmDirectExchange,
                                        @Qualifier("confirmQueue") Queue confirmQueue) {
        return BindingBuilder.bind(confirmQueue).to(confirmDirectExchange).with(CONFIRM_ROUTING_KEY);
    }


    //备份交换机
    public static final String BACKUP_EXCHANGE_NAME = "backup_exchange";
    //备份队列
    public static final String BACKUP_QUEUE_NAME = "backup_queue";
    //报警队列
    public static final String BACKUP_WARN_QUEUE_NAME = "backup_warn_queue";

    //广播扇出
    @Bean
    public FanoutExchange backupExchange() {
        return new FanoutExchange(BACKUP_EXCHANGE_NAME);
    }

    @Bean
    public Queue backupQueue() {
        return QueueBuilder.durable(BACKUP_QUEUE_NAME).build();
    }

    @Bean
    public Queue warnQueue() {
        return QueueBuilder.durable(BACKUP_WARN_QUEUE_NAME).build();
    }

    //备份交换机绑定备份队列和报警队列
    @Bean
    public Binding backupQueueBindingExchange(@Qualifier("backupExchange") FanoutExchange backupExchange,
                                              @Qualifier("backupQueue") Queue backupQueue) {
        return BindingBuilder.bind(backupQueue).to(backupExchange);
    }

    @Bean
    public Binding warnQueueBindingExchange(@Qualifier("backupExchange") FanoutExchange backupExchange,
                                            @Qualifier("warnQueue") Queue warnQueue) {
        return BindingBuilder.bind(warnQueue).to(backupExchange);
    }


}
